<template>
    <div>
        <div class="add-btn">
            <el-button size="small" type="success" @click="addVisible = true">添加</el-button>
        </div>

        <div>
            <el-table :data="listData" class="list-data" border style="width: 100%">
                <el-table-column prop="id" label="" width="60"></el-table-column>
                <el-table-column prop="title" label="标题"></el-table-column>
                <el-table-column align="center" label="操作" width="150">
                    <template #default="scope">
                        <el-button size="small" type="danger" @click="preDelete(scope.row)"
                            >删除</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <el-dialog title="" v-model="addVisible" width="300px" center>
            <div class="del-dialog-cnt">
                <el-input
                    v-model="formData.title"
                    style="width: 240px"
                    placeholder="Please input"
                    @keyup.enter="add"
                />
            </div>
            <template #footer>
                <span>
                    <el-button @click="addVisible = false">取 消</el-button>
                    <el-button type="primary" @click="add">确 定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 删除提示框 -->
        <el-dialog title="提示" v-model="deleteVisible" width="300px" center>
            <div class="del-dialog-cnt">确定删除:{{ deleteItem.title }}？</div>
            <template #footer>
                <span>
                    <el-button @click="deleteVisible = false">取 消</el-button>
                    <el-button type="primary" @click="deleteRow">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { post, get } from '@/util/request'
import router from '@/router'

const addVisible = ref(false)
const formData = ref({
    title: ''
})

const deleteVisible = ref(false)
const listData = ref([])
const deleteItem = ref(null)

// 记录要删除的条目
const preDelete = (inst) => {
    deleteItem.value = inst
    deleteVisible.value = true
}

// 删除条目
const deleteRow = () => {
    get('/category/delete?id=' + deleteItem.value.id).then((resp) => {
        getData()
        deleteVisible.value = false
    })
}

const getData = () => {
    get('/category/get').then((resp) => {
        listData.value = resp.insts
    })
}

onMounted(() => {
    getData()
})

const add = () => {
    post('/category/add', formData.value).then((resp) => {
        getData()
        addVisible.value = false
    })
}
</script>
